import time

import tushare as ts
from tools.dbTool import dbTool
import schedule

ts.set_token('481d370707b3ed8567ec341857fbfdbf13b3e844db9afe355e332e5d')
tsp = ts.pro_api()


def getData(name, funName, table=None, **params):
    print('保存数据:' + name)
    if funName in ['pro_bar']:
        tspFun = getattr(ts, funName)
    else:
        tspFun = getattr(tsp, funName)
    res = tspFun(**params)
    if table is None:
        table = 'ts_' + funName
    cnt = dbTool.saveAll(table, res, tableComment=name)
    print('更新条数:' + str(cnt))


def getAllCode():
    df = tsp.stock_basic()
    return df['ts_code']


def oneJob():
    param = {'start_date': 20100101}  # 'end_date': 19851231
    getData('上市公司', 'stock_basic')
    # getData('沪深成分股', 'hs_const', hs_type='SZ')  # SH,SZ
    # getData('上市公司其他信息', 'stock_company', table='company_ext', exchange='SZSE')  # SSE上交所 SZSE深交所
    # getData('中国历年gdp', 'cn_gdp', start_q='1980Q1', end_q='2020Q3')  # SH,SZ
    # getData('居民消费价格指数', 'cn_cpi', **mRange)
    # getData('工业生产者出厂价格指数', 'cn_ppi', **mRange)
    # getData('货币供应量', 'cn_m', **mRange)
    # getData('指数基本信息', 'index_basic')
    # getData('指数周线行情', 'index_weekly', ts_code='000001.SH')
    # getData('利润表/业绩报表', 'income', **{'ts_code': '000001.SZ', 'start_date': 20100101})


def getDailyStartDate(tscode, defaultDate):
    day = defaultDate
    res = dbTool.getPdList(f"select max(trade_date) as maxDate from ts_daily_hfq where ts_code='{tscode}'")
    if len(res) != 0 and res[0]['maxDate'] is not None:
        day = res[0]['maxDate']
    print('开始日期:' + str(day))
    return str(day)


def multiJob():
    codes = getAllCode()
    continueCode = ''
    for code in codes:
        if continueCode == '' or code == continueCode:
            continueCode = ''
            print('code:' + code)
            startDate = '20100101'
            # getData('利润表/业绩报表', 'income', ts_code=code, start_date=startDate)
            getData('每日k线行情,后复权', 'pro_bar', table='ts_daily_hfq', adj='hfq', ts_code=code,
                    start_date=getDailyStartDate(code, startDate))


def test():
    # getData('利润表/业绩报表', 'income', **{'ts_code': '000001.SZ', 'start_date': 20100101})
    df = ts.pro_bar(ts_code='000001.SZ', adj='qfq', start_date='20180101', end_date='20241205')
    for date in df['trade_date']:
        print(date)
    pass


def timingRun():
    df = ts.pro_bar(ts_code='000001.SZ', adj='qfq', start_date='20180101', end_date='20241205')
    for date in df['trade_date']:
        print(date)
        getData('个股资金流向(东方财富)', 'moneyflow_dc', trade_date=date)  # 每天最多访问2次
        time.sleep(1860)  # 每31分钟执行一次任务
    pass


if __name__ == '__main__':
    # oneJob()
    # multiJob()
    # test()
    timingRun()
    print("over")
